﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Mvc;
using NHibData.Attributes;
using StudyEnglish.Models;
using StudyEnglish.Service;
using File = StudyEnglish.Model.File;

namespace StudyEnglish.Controllers
{
    public class FilesController : BaseController
    {
        #region PATH
        public static string ServerFilesPath
        {
            get { return ConfigurationManager.AppSettings["ServerFilesPath"]; }
        }

        public static int MaxFileSize
        {
            get { return int.Parse(ConfigurationManager.AppSettings["MaxFileSize"]); }
        }

        public static string ClientFilesStoragePath
        {
            get { return ConfigurationManager.AppSettings["ClientFilesStoragePath"]; }
        }
        #endregion



        public static string FileFullPath(File file)
        {
            return Path.Combine(ServerFilesPath, file.ServerFileName);
        }

        public ActionResult Index()
        {
            return View();
        }
        
        [Transaction]
        public string UploadFiles(string token, HttpPostedFileBase FileData)
        {
            var httpReportFile = FileData;
            
            string result;
            var file = new File
                           {
                               InitialFileName = httpReportFile.FileName,
                               ServerFileName = Guid.NewGuid().ToString(),
                               FileSize = httpReportFile.ContentLength,
                               FileType = httpReportFile.ContentType
                           };

            if(file.FileSize > MaxFileSize)
            {
                result = "File is too big";
            }
            else
            {
                try
                {
                    httpReportFile.SaveAs(FileFullPath(file));
                    DataService.FileService.SaveFile(file);
                    result = "OK";
                }
                catch (Exception e)
                {
                    result = "Can't save file";    
                }
            }
            return result;
        }

        public DownloadFileResult PreviewFile(int id)
        {
            var file = DataService.FileService.GetFileById(id);
            return new DownloadFileResult(FileFullPath(file), file.InitialFileName);
        }

        [Transaction]
        public ActionResult DeleteFile(int id)
        {
            var file = DataService.FileService.GetFileById(id);
            var path = FileFullPath(file);

            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }
            DataService.FileService.DeleteFile(file);
            return RedirectToAction("Index", "Library");
        }


        [Transaction]
        public ActionResult UploadCompleteLevel()
        {
            var initialPath = ClientFilesStoragePath;
            var files = Directory.GetFiles(initialPath, "*", SearchOption.AllDirectories);
            var list = new List<FileModel>();
            foreach(var file in files)
            {
                var r = SaveFile(file);
                list.Add(new FileModel(){IsSaved = r, File = file});
            }
            return View(list);
        }

        private bool SaveFile(string filePath)
        {
            var fileInfo = new System.IO.FileInfo(filePath);
            var filename = fileInfo.Name;

            var fileWithGivenName = DataService.FileService.FindByName(filename);
            if (fileWithGivenName == null)
            {

                var file = new File
                               {
                                   InitialFileName = filename,
                                   ServerFileName = Guid.NewGuid().ToString(),
                                   FileSize = (int) fileInfo.Length,
                                   FileType = fileInfo.Extension,
                                   InitialFilePath = filePath
                               };

                
                System.IO.File.Copy(filePath, FileFullPath(file));
                DataService.FileService.SaveFile(file);
                return true;
            }
            return false;
        }

        public class FileModel
        {
            public bool IsSaved;
            public string File;
        }
    }
}
